import torch


class Net(torch.nn.Module):

    def __init__(self, n_feature, n_output):
        super(Net, self).__init__()
        # 加入一个隐藏层
        self.hidden = torch.nn.Linear(n_feature, 100)
        # 线性回归模型
        self.predict = torch.nn.Linear(100, n_output)

    def forward(self, x):
        out = self.hidden(x)
        out = torch.relu(out)  # 加入非线性的运算
        out = self.predict(out)
        return out



# 1、解析数据
import numpy as np
import re

ff = open('../data/housing.data').readlines()  # 读取所有行
data = []

for item in ff:
    out = re.sub(r'\s{2,}', ' ', item).strip()  # 将多空格合并为一个空格,并去掉换行符
    # print(out)
    data.append(out.split(' '))

data = np.array(data).astype(np.float32)  # 转换为numpy类型
# print(笔记.md.shape) # (506, 14)

# 将数据切分为x,y
x = data[:, 0:-1]
y = data[:, -1]
# print(x.shape, y.shape) # (506, 13) (506,)

# 划分训练集和测试集
x_train = x[0:496, ...]
y_train = y[0:496, ...]
x_test = x[496:, ...]
y_test = y[496:, ...]

# 加载模型
net = torch.load('../model/model_k1.pkl')

loss_func = torch.nn.MSELoss()  # 使用均方差损失函数

# 6、预测
x_data = torch.tensor(x_test, dtype=torch.float32)
y_data = torch.tensor(y_test, dtype=torch.float32)

# 前向推导
pred = net.forward(x_data)
# print(pred.shape, y_data.shape) # torch.Size([496, 1]) torch.Size([496])
# 维度不对，需要调整
pred = torch.squeeze(pred)
# print(pred.shape, y_data.shape)  # torch.Size([496]) torch.Size([496])
loss_test = loss_func(pred, y_data) * 0.001
print('loss_test:{}'.format(loss_test))